package paa.crawlers.delicious;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class Main {

	public static void main(String[] args) throws Exception {
		if (args == null || args.length < 1) {
			System.err.println("usage: java " + Main.class + " <in file> <out dir>");
			System.exit(1);
		}
		
		File file = new File(args[0]);
		File dir = new File(args[1]);
		
		if (!file.exists()) {
			System.err.println("In file does not exist.");
			System.exit(1);
		}
		
		if (!dir.isDirectory() || dir.listFiles().length < 0) {
			System.err.println("Out dir is not a directory or is not empty, exiting.");
			System.exit(1);
		}
		
		BufferedReader reader = null;
		UserExtractor ue = new UserExtractor();
		
		try {
			reader = new BufferedReader(new FileReader(file));
			String line;
			
			while((line = reader.readLine()) != null) {

				BufferedWriter w = null;
				try {
					DeliciousUser user = ue.extractUser(line);
					File outdir = new File(dir.getAbsolutePath() + File.separator + user.getId().charAt(0));
					if (!outdir.exists()) {
						outdir.mkdirs();
					}
					
					File userfile = new File(outdir + File.separator + user.getId());
					w = new BufferedWriter(new FileWriter(userfile));
					w.write("#user: " + user.getId());
					w.newLine();
					w.write("#urls: " + user.getUrls());
					w.newLine();
					w.write("#fans: " + user.getFans());
					w.newLine();
					w.write("#network: " + user.getNetwork());
					w.flush();
					w.close();
				} catch (Exception e) {
					System.err.println("Error occurred at user " + line + " -> " + e );
				} finally {
					if (w != null) w.close();
				}
				
				Thread.sleep(10000);
			}
			
			reader.close();
		} finally {
			if (reader != null) reader.close();
		}
		
	}
	
}
